/**
 * Created by Jack Xue on 20101026
 */
package org.code.jack.jweberp.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.code.jack.jweberp.core.FrameworkEngine;
import org.code.jack.jweberp.core.WebForm;
import org.springframework.util.StringUtils;

public class BaseAction extends DispatchAction {
	
	private final static Logger logger = Logger.getLogger(BaseAction.class);
	/**
	 * 替代Struts的ActionForm,如webForm.form2Obj(User.class),则把视图层传递到Servlet中参数对应的值自动赋值给PO对象
	 */
	protected static WebForm webForm = null;
	/**
	 * 记录请求地址的根目录,以"/"开关,但不是以"/"结尾.如/User.do
	 */
	protected static String veerUrl = null;
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		
		webForm = FrameworkEngine.creatWebForm(request);
		veerUrl = request.getServletPath();

		// 所请求的方法
		String method = request.getParameter(mapping.getParameter());
		
		// 添加数据时加入防重复提交令牌
		if ("add".equals(method)) {
			saveToken(request);
			request.setAttribute("token", request.getSession().getAttribute(Globals.TRANSACTION_TOKEN_KEY));
		} else if ("save".equals(method)) {
			if (!isTokenValid(request, true)) {
				request.setAttribute("msg", "重复提交数据");
				request.setAttribute("newurl", veerUrl);
				logger.error("重复提交数据");
				return mapping.findForward("list");
			}
			// 数据列表显示时传递一些查询参数及JAVA工具类到客户端
		} else if ("list".equals(method) || !StringUtils.hasText(method)) {
			request.setAttribute("orderBy", request.getAttribute("orderBy"));
			request.setAttribute("orderType", request.getAttribute("orderType"));
			// request.setAttribute("CommUtil", CommUtil.class);
		}
		return super.execute(mapping, form, request, response);
	}

}
